/*
 * Copyright 2009 Jamie Gennis
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.code.gwt.remoteaction.server;

import com.google.code.gwt.remoteaction.client.Action;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * A parameter extractor that gets the parameter value from a getter method in
 * the Action instance.
 *
 * @author jgennis
 */
public class GetterParameterExtractor implements ParameterExtractor {

  protected final Method getter;

  /**
   * Initialize a new GetterParameterExtractor with a given getter method.
   *
   * @param getter the getter instance method to use to extract the parameter
   * @throws IllegalArgumentException if the declaring class of the given
   *         getter method does not implement the Action interface; if the
   *         given getter method is not a 0-argument method
   */
  public GetterParameterExtractor(Method getter) throws IllegalArgumentException {
    if (!Action.class.isAssignableFrom(getter.getDeclaringClass())) {
      throw new IllegalArgumentException("The declaring class of the 'getter' method argument " +
          "must implement the " + Action.class.getCanonicalName() + " interface");
    }
    if (getter.getParameterTypes().length > 0) {
      throw new IllegalArgumentException("The 'getter' method argument must not take any " +
          "arguments");
    }
    this.getter = getter;
  }

  /**
   * Extract the parameter from an Action instance using the getter method.
   *
   * @param action the action instance
   * @return the extracted parameter
   * @throws IllegalArgumentException if the Action instance is not an instance
   *         of the getter method's declaring class
   */
  public Object extract(Action action) throws IllegalArgumentException {
    try {
      return getter.invoke(action);
    } catch (IllegalAccessException ex) {
      throw new RuntimeException(ex);
    } catch (InvocationTargetException ex) {
      throw new RuntimeException(ex);
    }
  }
}
